package foroweb.security;

import foroweb.ejb.InterfaceBusquedas;
import foroweb.entidades.Usuario;
import java.util.*;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;

public class UserDetailsServiceImpl implements UserDetailsService {    

    //Atributos
    private InterfaceBusquedas ib;

    //Getters y Setters
    public void setIb(InterfaceBusquedas ib) {
        this.ib = ib;
    }

    //Metodos
     @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        Usuario user =ib.buscarUsuario(username);
        if (user == null)
            throw new UsernameNotFoundException("User not found: " + username);
        else {
            return makeUser(user);
        }
    }
    private org.springframework.security.core.userdetails.User makeUser(Usuario user) {
        User u=new User(user.getNick(), user.getPassword(), user.isActivo(), true, true, true, makeGrantedAuthorities(user));
        return u;
    }
    private Collection<GrantedAuthority> makeGrantedAuthorities(Usuario user) {
        Collection<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
        result.add(new SimpleGrantedAuthority(user.getRol()));
        return result;
    }

    //Polimorfismo
   
}